package com.thinkgem.jeesite.modules.sys.web;

import com.thinkgem.jeesite.common.annotation.MobileApi;
import com.thinkgem.jeesite.common.annotation.MobileApiAnonymous;
import com.thinkgem.jeesite.common.utils.FileUtils;
import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.web.BaseMobileApiController;
import com.thinkgem.jeesite.modules.devmng.entity.CommonAtta;
import com.thinkgem.jeesite.modules.devmng.service.CommonAttaService;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017-12-8.
 */
@MobileApi
@Controller
@RequestMapping("/mobile-api/atta")
public class AttaMobileController extends BaseMobileApiController {

    @Value("${web.upload.path}")
    private String webUploadPath;

    @Value("${web.upload.url.prefix}")
    private String webUploadUrlPrefix;

    @Autowired
    private CommonAttaService commonAttaService;

    @PostConstruct
    public void init() {
        if (!StringUtils.endsWith(webUploadPath, "/")) {
            webUploadPath += "/";
        }
        if (!StringUtils.endsWith(webUploadUrlPrefix, "/")) {
            webUploadUrlPrefix += "/";
        }
    }

    @ResponseBody
    @RequestMapping("/upload")
    public Map<String, String> upload(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String saveName = IdGen.uuid();
        if (StringUtils.isNotEmpty(extension)) {
            saveName = saveName + "." + extension;
        }
        try {
            file.transferTo(new File(webUploadPath + saveName));
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }

        CommonAtta commonAtta = new CommonAtta();
        commonAtta.setAttaGuid(saveName);
        commonAtta.setAttaContentType(file.getContentType());
        commonAtta.setAttaOriname(file.getOriginalFilename());
        commonAtta.setAttaSize(file.getSize());
        commonAtta.setAttaPath(webUploadPath);
        String attaUrl = webUploadUrlPrefix + saveName;
        commonAtta.setAttaUrl(attaUrl);
        commonAttaService.save(commonAtta);
        Map<String, String> map = new HashMap<String, String>();
        map.put("url", attaUrl);
        return map;
    }

    @MobileApiAnonymous
    @RequestMapping("/download/{attaGuid:[a-zA-Z0-9\\.]+}")
    public void download(@PathVariable("attaGuid") String attaGuid, HttpServletResponse response) throws Exception {
        //下载文件路径
        File file = new File(webUploadPath + attaGuid);
//        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        CommonAtta commonAttaQuery = new CommonAtta();
        commonAttaQuery.setAttaGuid(attaGuid);
        List<CommonAtta> commonAttaList = commonAttaService.findList(commonAttaQuery);
        if (commonAttaList.size() == 0) {
            return;
        }
        CommonAtta commonAtta = commonAttaList.get(0);
        String filename = commonAtta.getAttaOriname();
        String downloadFielName = new String(filename.getBytes("UTF-8"), "iso-8859-1");
        //通知浏览器以attachment（下载方式）打开图片
//        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
//        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//        headers.set("Content-Type", commonAtta.getAttaContentType());
//        headers.setContentType(MediaType.parseMediaType(commonAtta.getAttaContentType()));
//        headers.setCacheControl();
//        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
//                headers, HttpStatus.OK);
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setHeader("Content-disposition", "attachment; filename=" + downloadFielName);
        response.setContentType(commonAtta.getAttaContentType());
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(FileUtils.readFileToByteArray(file));
        responseOutputStream.flush();
        responseOutputStream.close();
    }

}
